package hgx.spring.cloud.lession.productrepertory.hystrix;/**
 * Created by liujun on 2018/4/21.
 */

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;

import java.util.List;
import java.util.Random;

import hgx.spring.cloud.lession.productrepertory.api.ProductRepository;
import hgx.spring.cloud.lession.productrepertory.vo.ProductVo;
import hgx.spring.cloud.lession.productrepertory.vo.ReponseProductListVo;

/**
 * 查询所有产品
 * @author hugx
 * @create 2018-04-21 10:31
 */
public class ProductFindAllHystrixCommand extends HystrixCommand<ReponseProductListVo> {
    private ProductRepository productRepository;
    private static Random random = new Random();
    private static final  HystrixCommandKey FindAll_Key=HystrixCommandKey.Factory.asKey("product_findAll");

    public ProductFindAllHystrixCommand(ProductRepository productRepository) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(ProductCommandEnum.Product_Get_Set_GroupKey.getKey())).andCommandKey(FindAll_Key));
        this.productRepository = productRepository;
    }


    @Override
    protected ReponseProductListVo run() throws Exception {
        long startTime = System.currentTimeMillis();
        int sleepTime = random.nextInt(1000);
        System.out.println("执行 断路器命令的run() 方法 , sleepTime: " + sleepTime + "  , keyName: " + getCommandKey().name());

        ReponseProductListVo reponse = new ReponseProductListVo();
        List<ProductVo> list = productRepository.findAll();
        if (list != null && !list.isEmpty()) {
            reponse.setProductVos(list);
            reponse.success();
        }

        System.out.println("3: ----------------run() ,耗时: " + (System.currentTimeMillis() - startTime));
        return reponse;
    }

    @Override
    protected ReponseProductListVo getFallback() {
        System.out.println("3.1: ----------------getFallback()  ");
        ReponseProductListVo reponse = new ReponseProductListVo();
        return reponse;
    }

    @Override
    protected String getCacheKey() {
        /*根据查询条件置入缓存*/
        System.out.println("4.1-------------------------从缓存中获取数据");
        String result=super.getCacheKey();
        System.out.println("4.2-------------------------从缓存中获取数据 ， cacheKey: "+result);
        return result;
    }

    public static void flushCache(){
        /*刷新缓坡，根据查询条件进行清理*/
        HystrixRequestCache.getInstance(FindAll_Key, HystrixConcurrencyStrategyDefault.getInstance()).clear("");
    }
}
